<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="数据库" prop="dbId">
          <el-tree-select
            v-model="queryParams.dbId"
            placeholder="选择数据库"
            :data="dbSourceOptions"
            filterable
            check-strictly
            :render-after-expand="false"
            style="width: 220px"
          />
        </el-form-item>

        <el-form-item label="BinLog" prop="binlogId">
          <el-tree-select
            v-model="queryParams.binlogId"
            placeholder="选择BinLog文件"
            :data="binLogOptions"
            filterable
            check-strictly
            :render-after-expand="false"
            style="width: 270px"
          />
        </el-form-item>

        <el-form-item prop="executedTime" label="执行时间">
          <el-date-picker
            v-model="queryParams.executedTime"
            :editable="false"
            type="datetimerange"
            range-separator="~"
            start-placeholder="开始时间"
            end-placeholder="截止时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 370px"
          />
        </el-form-item>

        <el-form-item prop="position" label="起始位置">
          <el-col :span="11">
            <el-form-item prop="startPosition">
              <el-input
                v-model="queryParams.startPosition"
                placeholder="开始位置"
                style="width: 140px"
              />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item prop="endPosition">
              <el-input
                v-model="queryParams.endPosition"
                placeholder="结束位置"
                style="width: 140px"
              />
            </el-form-item>
          </el-col>
        </el-form-item>

        <el-form-item class="search-buttons">
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="hover" class="data-table">
      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="executedList"
        highlight-current-row
        border
        class="data-table__content"
      >
        <el-table-column label="数据库" prop="dbName" align="center" width="150" />
        <el-table-column label="BinLog文件" prop="binlogFile" align="center" width="150" />
        <el-table-column
          label="已执行SQL"
          prop="sqlStatement"
          :show-overflow-tooltip="true"
          align="center"
          min-width="280"
        />
        <el-table-column label="开始位置" prop="startPosition" align="center" width="120" />
        <el-table-column label="结束位置" prop="endPosition" align="center" width="120" />
        <el-table-column label="执行时间" prop="executedTime" align="center" width="170" />
        <el-table-column fixed="right" label="操作" align="center" width="120">
          <template #default="scope">
            <el-button
              type="primary"
              size="default"
              link
              icon="CopyDocument"
              @click="copySql(scope.row.sqlStatement)"
            >
              复制
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="fetchData"
      />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import DbSourceAPI from "@/api/mysql/dbsource.api";
import BinLogAPI from "@/api/mysql/binlog.api";
import ExecutedAPI, { ExecutedPageQuery, ExecutedPageVO } from "@/api/mysql/executed.api";

defineOptions({
  name: "Execute",
  inheritAttrs: false,
});

const queryFormRef = ref();
const permTreeRef = ref();
const loading = ref(false);
const total = ref(0);

// 查询表单
const queryParams = reactive<ExecutedPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

// 表格数据
const executedList = ref<ExecutedPageVO[]>();
const permKeywords = ref("");
const dbSourceOptions = ref<OptionType[]>();
const binLogOptions = ref<OptionType[]>();

// 获取数据库列表
async function fetchDbSource() {
  dbSourceOptions.value = await DbSourceAPI.getOptions();
}

// 获取BinLog列表
async function fetchBinLogList() {
  const dbId = queryParams.dbId;
  binLogOptions.value = await BinLogAPI.getOptions(dbId);
}

// 获取数据
function fetchData() {
  loading.value = true;
  ExecutedAPI.getPage(queryParams)
    .then((data) => {
      executedList.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 查询（重置页码后获取数据）
function handleQuery() {
  queryParams.pageNum = 1;
  fetchData();
}

// 重置查询
function handleResetQuery() {
  queryParams.dbId = undefined;
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  fetchData();
}

// 解析Binlog
function copySql(sql?: string) {
  // 创建一个临时的 textarea 元素
  const textarea = document.createElement("textarea");
  textarea.value = sql || "";
  textarea.style.position = "fixed"; // 防止滚动条出现
  textarea.style.opacity = "0"; // 隐藏
  document.body.appendChild(textarea);

  // 选中并复制内容
  textarea.select();
  document.execCommand("copy");

  // 移除临时元素
  document.body.removeChild(textarea);

  // 提示用户
  ElMessage.success("复制成功");
}

// 权限筛选
watch(permKeywords, (val) => {
  permTreeRef.value!.filter(val);
});

// 更新binlog列表
watch(
  () => queryParams.dbId,
  async (newVal) => {
    if (newVal) {
      queryParams.binlogId = undefined;
      await fetchBinLogList();
    } else {
      binLogOptions.value = [];
    }
  }
);

// 数据挂载
onMounted(() => {
  fetchDbSource();
  handleQuery();
});
</script>
